import base64
import re

import datetime as dt


from flask import Blueprint, render_template, jsonify, redirect, url_for, session
from flask import request

from util.detailfunction import displayinfo, searchscore, displayrooms, displayrestaurant, displaypolicy, \
    displaydescribe, displayfac
from util.mainfunction import displayorderroom, orderdisplay, td, checkoid, delete, reservation,add
from util.searchfunction import shaixuan, brandandfac, searchche, sortprice, pointlist, dislist, fliter, sortsus, \
    sortdis, sortp

bp=Blueprint("search",__name__)

@bp.route("/hotel",methods=['GET', 'POST'])
def hotel():

    if session.get('hid')==None:
        hid=request.args.get('hid')
        session['hid']=hid
    else:
        if session.get('hid')!=request.args.get('hid'):
            hid=request.args.get('hid')
        else:
            hid=session.get('hid')
    print(hid)
    pro1 = displayinfo(hid)
    pn = pro1[0]['photonum']
    photolist = []
    # hid=str(500)
    fold = int(int(hid) / 1000) * 1000
    print(fold)
    for i in range(1, pn + 1):
        strt = hid + "_" + str(i) + ".jpg"
        url = "../static/img/内部image/image/" + str(int(fold)) + "/" + strt
        photolist.append(url)
    if len(photolist) < 8:
        v = 8 - len(photolist)
        for i in range(0, v):
            photolist.append("../static/img/1_1.jpg")
    print(photolist)
    p2 = searchscore(hid)
    people=session.get('adult')+session.get('child')

    p3 = displayrooms(hid,people)
    list1 = []
    for i in p3:
        list1.append(i['roomid'])
    session['roomtype'] = list1
    p4 = displayrestaurant(hid)
    p5 = displaypolicy(hid)
    p6 = displaydescribe(hid)
    p7 = displayfac(hid)
    checkin=session.get('checkin')
    for i in p3:
        cancel=i['roomcancel']
        if cancel=="免费取消":
            realcancel=str(checkin)+"中午12：00之前可免费取消"
            i['roomcancel']=realcancel
    if request.method == 'GET':
        return render_template("hotel.html", pro1=pro1,p2=p2,p3=p3,p4=p4,p5=p5,p6=p6,p7=p7,photolist=photolist,checkin=checkin)
    else:
        test=session.get('roomtype')
        order = []
        t=request.get_data()
        print(t)
        for i in test:
            temp=request.form.get(str(i))
            print(temp)
            if temp!='0':
                result = dict(rnum=temp, rid=i)
                order.append(result)
        if len(order)==0:
            print('刷新')
            request.method=='GET'
            print(request.method)
            #return render_template("hotel.html", pro1=pro1, p2=p2, p3=p3, p4=p4, p5=p5, p6=p6, p7=p7,photolist=photolist)
            return redirect(url_for("search.hotel"))
        session['order']=order
        print(session.get('order'))
        session['hid']=''
        session['now']='hotel'
        if (session.get('email')==None):
            return redirect("/register")
        return redirect(url_for("search.commit"))

@bp.route("/",methods=['GET', 'POST'])
def bookingmain():
    print(session.get('email'))
    if request.method == 'GET':
        if session.get('islog')==None:
            session['islog']=0
        islog=session.get('islog')
        return render_template("headerweb.html",islog=islog)
    else:
        temp=request.get_data()
        print(temp)
        query = request.form.get('city')
        startdate=request.form.get('start')
        enddate=request.form.get('end')
        adult=request.form.get('adult')
        child=request.form.get('child')
        room=request.form.get('room')

        if (startdate=='') or (enddate==''):
            print(11111)
            return redirect(url_for("search.bookingmain"))
        if (startdate==None) or (enddate==None):

            startdate=dt.datetime.now()

            enddate=(dt.datetime.now() + dt.timedelta(days=1))
            iy = startdate.year
            im = startdate.month
            id = startdate.day
            startdate = str(im) + "/" + str(id) + "/" + str(iy)
            oy = enddate.year
            om = enddate.month
            od = enddate.day
            enddate = str(om) + "/" + str(od) + "/" + str(oy)
            print(startdate,enddate)
        a = dt.datetime.strptime(startdate, '%m/%d/%Y' )
        checkin = dt.datetime.strftime(a, '%Y-%m-%d')
        b = dt.datetime.strptime(enddate, '%m/%d/%Y')
        checkout = dt.datetime.strftime(b, '%Y-%m-%d')
        print(checkin,checkout)
        d1 = dt.datetime.strptime(checkin, '%Y-%m-%d')
        iny=d1.year
        inm=d1.month
        ind=d1.day
        checkintime=str(iny)+"年"+str(inm)+"月"+str(ind)+"日"
        d2 = dt.datetime.strptime(checkout, '%Y-%m-%d')
        outy=d2.year
        outm=d2.month
        outd=d2.day
        checkouttime=str(outy)+"年"+str(outm)+"月"+str(outd)+"日"
        delta = d2 - d1
        print(delta.days)

        session['query']=query
        session['checkin'] = checkintime
        session['checkout'] = checkouttime
        session['adult'] = adult
        session['child'] = child
        session['room'] = room
        session['day']=delta.days
        list1=[[],[],[]]
        session['fliter']=list1
        print(session)
        return redirect(url_for("search.searchlist"))

@bp.route("/searchlist",methods=['GET', 'POST'])
def searchlist():
    if request.method == 'GET':
        flitercon=session.get('fliter')
        print(flitercon)
        typelist=[]
        pl = []
        dl = []
        if flitercon:
            typelist=flitercon[0]
            pl=flitercon[1]
            dl=flitercon[2]
        print(typelist,pl,dl)
        fliterlist=[]
        for i in typelist:
            if i=='公寓':
                fliterlist.append('apartment')
            if i=='酒店':
                fliterlist.append('hotel"')
            if i=='旅馆':
                fliterlist.append('guestroom')
            if i=='民宿':
                fliterlist.append('homestay')
        for i in pl:
            fliterlist.append(i)
        for i in dl:
            fliterlist.append(i)
        query =session.get('query')
        day=session.get('day')
        room=session.get('room')
        adult=session.get('adult')
        if day==None or room==None:
            session['day']=1
            session['room']=1
            session['child']=1
            session['adult']=1
            adult=1
            day=1
            room=1
        result=searchche(query,int(day)*int(room))
        typedic=shaixuan(result)
        pointdic=pointlist(result)
        disdic=dislist(result)
        print(pointdic, disdic)
        guolv=fliter(typelist,pl,dl,result)
        result=guolv
        tlist = []
        tlist.append(query)
        tlist.append(len(result))#查询结果数量
        session['fliter']=[]
        for i in result:
            img="../static/img/image/"+str(i['hid'])+".jpg"
            i['img']=img
        print("查看速度")
        print("排序法则",session.get('sort'))
        if session.get('sort'):
            if session.get('sort')=="1'":
                r1 = sortprice(result)
                result=r1
            if session.get('sort') =="2'":
                print("准备排序")
                r2=sortsus(result)
                result = r2
            if session.get('sort') == "3'":
                r3=sortdis(result)
                result = r3
            if session.get('sort') == "4'":
                r4=sortp(result)
                result = r4
        return render_template("listOfCity.html",test1=result,test=tlist,type=typedic,point=pointdic,dis=disdic,adult=adult,day=day)
    else:
        data=request.get_data()
        a=str(data).split('=')[0]
        print(a)

        if data:
            history=[[],[],[]]
            if a=="b'apartment":
                history[0].append("公寓")
            if a == "b'hotel":
                history[0].append("酒店")
            if a == "b'guestroom":
                history[0].append("旅馆")
            if a == "b'homestay":
                history[0].append("民宿")
            if a == "b'fabulous":
                history[1].append(9)
            if a == "b'excellent":
                history[1].append(8)
            if a == "b'great":
                history[1].append(7)
            if a == "b'enjoyable":
                history[1].append(6)
            if a == "b'near":
                history[2].append(1)
            if a == "b'close":
                history[2].append(3)
            if a == "b'moderate":
                history[2].append(5)
            if a=="b'sortOrder":
                b = str(data).split('=')[1]
                session['sort']=b
            session['fliter']=history
            print(session.get('fliter'))
            return redirect(url_for("search.searchlist"))
        session['hid']=''
        print("hid",session.get('hid'))
        return redirect(url_for("search.hotel"))

@bp.route("/commit",methods=['GET', 'POST'])
def commit():
   global commitdb
   if request.method=='GET':
       rooms=[]
       hid=''
       order=session.get('order')
       checkin=session.get('checkin')
       checkout=session.get('checkout')
       time=session.get('day')
       sum=0
       for i in order:
           result=displayorderroom(str(i['rid']))
           hid=result[0]['hid']
           print(result[0]['price'],time,int(i['rnum']))
           sum+=result[0]['price']*int(i['rnum'])*time
           result[0]['ordernum']=i['rnum']
           if result[0]['roomcancel']=="免费取消":
               str1=str(checkin)+"中午12：00之前可免费取消"
               result[0]['roomcancel']=str1
           rooms.append(result[0])
       img = "../static/img/image/" + str(hid) + ".jpg"
       print(hid)
       information=displayinfo(str(hid))
       fac=displaydescribe(str(hid))
       print("information",information)
       print('rooms',rooms)
       commitdb=rooms
       return render_template('reservation.html',img=img,information=information,fac=fac,room=rooms,checkin=checkin,checkout=checkout,time=time,price=sum)
   else:
       print(commitdb)
       for i in commitdb:
           reservation(i['roomid'],i['ordernum'])
           add(session.get('email'),i['hid'],i['roomid'],session.get('checkin'),session.get('checkout'),i['ordernum'],session.get('day'))
       return redirect(url_for("search.bookingmain"))
@bp.route("/fake",methods=['GET', 'POST'])
def chunluren():
    return redirect("/order?oid=null")

@bp.route("/order",methods=['GET', 'POST'])
def order():
    if request.method=="GET":
        deleteoid=request.args.get('oid')
        print(deleteoid)
        if deleteoid!="null":
            temp = checkoid(deleteoid)
            rid = temp[0][3]
            num = temp[0][6]
            td(rid, num)
            delete(deleteoid)
            return redirect("/order?oid=null")
        user=session.get('email')
        #user='213201199@seu.com'
        orderinfo=orderdisplay(str(user))
        resultlist=[]
        for i in orderinfo:
            r=displayorderroom(str(i[3]))
            temp=r[0]['price']
            r[0]['price']=temp*i[7]*i[6]
            r[0]['checkin']=i[4]
            r[0]['checkout']=i[5]
            img = "../static/img/image/" + str(r[0]['hid']) + ".jpg"
            r[0]['img'] = img
            r[0]['oid']=i[0]
            r[0]['room_num']=i[6]
            resultlist.append(r[0])
        return render_template("selfinformation.html",result=resultlist)
    else:
        pass
        return redirect(url_for())



